<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class ChannelService
{
    // 列表
    public static function index(): array
    {
        try {
            // 验证用户权限
            $auth = Auth::instance();
            // 预加载子渠道数据，减少查询次数
            $channels = \app\admin\model\UserChannel::with(['childChannels'])
                ->where('pid', 0)
                ->field('id,name')
                ->order('weigh desc')
                ->select()
                ?: [];

            // 格式化返回数据
            return [
                'code' => 200,
                'msg' => 'Successful',
                'state' => 'OK',
                'data' => $channels
            ];
        } catch (\Exception $e) {
            // 记录日志并返回错误信息
            return [
                'code' => 500,
                'msg' => 'Server Error',
                'state' => 'ERROR',
                'data' => []
            ];
        }
    }


    // 添加
    public static function add($data)
{
    if (!is_array($data)) {
        return ['code' => 400, 'msg' => 'Invalid data format', 'state' => 'INVALID_ARGUMENT', 'data' => null];
    }

    $auth = Auth::instance();
    $data['status'] = 'normal';
    $data['weigh'] = 0;

    // 验证规则 region_code，region_name，country_code 不为空且不重复
    $validate = new Validate([
        'name' => 'require',
        'region_code' => 'require',
        'region_name' => 'require',
        'country_code' => 'require',
    ], [
        'name.require' => 'Name is not empty',
        'region_code.require' => 'Region code is not empty',
        'region_name.require' => 'Region name is not empty',
        'country_code.require' => 'Country code is not empty',
    ]);

    if (!$validate->check($data)) {
        return ['code' => 400, 'msg' => $validate->getError(), 'state' => 'INVALID_ARGUMENT', 'data' => null];
    }

    // 启用事务将数据保存到数据库
    Db::startTrans();
    try {
        $result = \app\admin\model\UserChannel::create($data);

        if ($result) {
            Db::commit();
            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $result->toArray()];
        } else {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Failed', 'state' => 'FAILED', 'data' => []];
        }
    } catch (\Exception $e) {
        Db::rollback();
        return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => []];
    }
}


    // 编辑
    public static function edit($data)
    {
        // 验证规则 region_code，region_name，country_code 不为空且不重复
        $validate = new Validate([
            'name' => 'require',
        ], [
            'name.require' => 'Name is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();
        try {
            $result = \app\admin\model\UserChannel::update($data);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Update operation failed, no rows affected', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 验证$data['id']是否为空且为数字
        if (empty($data['id']) || !is_numeric($data['id'])) {
            return ['code' => 400, 'msg' => 'Invalid parameters', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        $id = (int)$data['id'];
        $hasChild = \app\admin\model\UserChannel::where('pid', $id)->exists();
        if ($hasChild) {
            // 请先删除子级数据
            return ['code' => 400, 'msg' => 'Please delete the child data first', 'state' => 'FAILED', 'data' => null];
        }

        // 启用事务删除数据
        Db::startTrans();
        try {
            $result = \app\admin\model\UserChannel::destroy($id);

            if ($result) {
                Db::commit();
                return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $result];
            } else {
                Db::rollback();
                return ['code' => 400, 'msg' => 'Failed', 'state' => 'FAILED', 'data' => null];
            }
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }



    // 查询
    public static function select($data)
    {
        $auth = Auth::instance();
        // 输入验证和默认值设置
        $pid = isset($data['pid']) && is_numeric($data['pid']) ? intval($data['pid']) : 0;

        // 统一查询
        $channel = \app\admin\model\UserChannel::where('pid', $pid)
            ->field('id,name')
            ->order('weigh desc')
            ->select();

        // 简化返回逻辑
        $state = $channel ? 'OK' : 'EMPTY';
        return [
            'code' => 200,
            'msg' => 'Successful',
            'state' => $state,
            'data' => $channel
        ];
    }


    // 查询
    public static function get_name(array $data): array
    {
        try {
            if (!isset($data['channel_id'])) {
                return ['code' => 400, 'msg' => 'Bad Request: channel_id is required', 'state' => 'ERROR', 'data' => null];
            }

            $channel = \app\admin\model\UserChannel::where('id', $data['channel_id'])->field('id,name')->find();

            if ($channel) {
                return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $channel];
            }

            return ['code' => 404, 'msg' => 'Channel not found', 'state' => 'EMPTY', 'data' => null];
        } catch (\Exception $e) {
            return ['code' => 500, 'msg' => 'Internal Server Error', 'state' => 'ERROR', 'data' => null];
        }
    }



    
}
